package com.kaikeba.dao.impl;

import com.kaikeba.dao.BaseAdminDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import com.kaikeba.util.DruidUtil;

public class AdminDaoMysql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "update EDMIN SET LOGINTIME=?,LOGINIP=? WHERE USERNAME = ?";
    private static final String SQL_LOGIN = "SELECT ID FROM EDMIN WHERE USERNAME=? AND PASSWORD=?";

    /**
     * 根据用户名，更新登录时间和IP
     *
     * @param username
     * @param date     ：在数据库中插入时间
     * @param ip       ：在数据库中插入IP信息
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        // 1、获取连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        int i = 0;
        // 预编译SqL语句
        try {
            preparedStatement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            // 将util的date 转化成 sql的 date
            java.sql.Date date1 = new java.sql.Date(date.getTime());
            // 填充参数
            preparedStatement.setDate(1,date1);
            preparedStatement.setString(2,ip);
            preparedStatement.setString(3,username);
            // 执行
            i = preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 释放资源
            DruidUtil.close(connection,preparedStatement,null);
        }

    }

    /**
     * 根据管理员的信息进行登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public boolean login(String username, String password) {
        // 1、获取连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        // 预编译SqL语句
        try {
            preparedStatement = connection.prepareStatement(SQL_LOGIN);
            // 填充参数
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            // 执行
            resultSet = preparedStatement.executeQuery();
            return resultSet.next();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 释放资源
            DruidUtil.close(connection,preparedStatement,resultSet);
        }
        return false;
    }
}
